package wnhz.com.business.shareshop.activity.classify.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseFragment;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.base.MyBaseFragment;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.rebateshop.activity.home.ShareFriandActivity;
import wnhz.com.business.rebateshop.activity.mine.AllOrderActivity;
import wnhz.com.business.shareshop.activity.classify.ClassifGoodsActivity;
import wnhz.com.business.shareshop.activity.home.EverydayPhoneActivity;
import wnhz.com.business.shareshop.activity.home.RebateGoodsDetailsActivityS;
import wnhz.com.business.shareshop.bean.F2TypeGoodsListBean;
import wnhz.com.business.shareshop.bean.ShoppingCartListBean;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 分类的二级界面
 */

public class ClassifGoodsFragment extends MyBaseFragment implements ActionBarClickListener, OnRefreshLoadmoreListener {
    @BindView(R.id.recycler_View)
    RecyclerView recyclerView;
    @BindView(R.id.empty_layout)
    LinearLayout empty_layout;
    @BindView(R.id.tv_msg)
    TextView tv_msg;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    ClassifGoodsActivity activity;
    private List<F2TypeGoodsListBean.InfoBean> itemdata = new ArrayList<>();
    private String cate_id;
    private String title;
    private BaseRVAdapter mBaseAdapter;
    private int page=0;

    public static ClassifGoodsFragment getInstance() {
        ClassifGoodsFragment cf = new ClassifGoodsFragment();
        return cf;
    }

    @Override
    protected void handleMsg(Message msg) {

    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_classif_phone, container, false);
        ButterKnife.bind(this, view);
        activity = (ClassifGoodsActivity) getActivity();
        cate_id = getArguments().getString("cate_id");
        title = getArguments().getString("title");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        initTestGallylist();
        return view;
    }

    private void loadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("cateId",cate_id);
        map.put("goods_type",4);
        map.put("page",page);
        /**
         根据指定商品分类查询商品数据
         @param   Str     token
         @param   Int     cateId      (一级分类id或二级分类id)  首次请求用一级分类ID，之后使用二级分类ID
         @param   Int     goods_type  1.拼团  2.返利  3.免费 4.共享
         @param   Int     page        页码
         */
        XUtil.Post(Url.GOODS_GETCATEGOODS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    if (re.equals("1")) {
                        Gson gson = new Gson();
                        F2TypeGoodsListBean f2TypeGoodsListBean = gson.fromJson(result, F2TypeGoodsListBean.class);
                        if (page == 0){
                            if (null != itemdata){
                                itemdata.clear();
                            }
                            itemdata = f2TypeGoodsListBean.getInfo();
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mBaseAdapter.notifyDataSetChanged();

                        }
                        initList();
                    }else if ("-1".equals(jsonObject.optString("re"))){
                        activity.MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 0){
                            mRefreshLayout.setVisibility(View.GONE);
                            empty_layout.setVisibility(View.VISIBLE);
                            activity.MyToast(jsonObject.optString("info"));
                            tv_msg.setText("暂无商品");
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
                            empty_layout.setVisibility(View.GONE);
                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    private void initTestGallylist() {
        recyclerView.setLayoutManager(new GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false));

        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        loadData();
    }

    private void initList() {

        //holder.setTextView(R.id.item_tv_rebatehome_info,itemdata.get(position).get());
        //跳转分享页面  (页面标题: 分享商品给好友)
        mBaseAdapter = new BaseRVAdapter(activity, itemdata) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_classify_phone;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                Glide.with(getActivity()).load(itemdata.get(position).getLogo_pic()).into(holder.getImageView(R.id.item_img_rebatehome));
                holder.setTextView(R.id.item_tv_rebatehome_name,itemdata.get(position).getGoods_name());
                holder.setTextView(R.id.item_tv_rebatehome_info,itemdata.get(position).getGoods_title() + " " + itemdata.get(position)
                .getGoods_des());
                holder.setTextView(R.id.item_tv_rebatehome_price,"押金"+itemdata.get(position).getPrice()+"元");
                holder.getView(R.id.item_tv_rebatehome_share).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转分享页面  (页面标题: 分享商品给好友)
                        startActivity(ShareFriandActivity.createIntent(getContext(),itemdata.get(position).getLogo_pic(),"",itemdata.get(position).getGoods_name(),itemdata.get(position).getGroup_price()));
                    }
                });
                holder.getView(R.id.item_rl_rebatehome).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(RebateGoodsDetailsActivityS.createIntent(activity, itemdata.get(position).getGoods_id(), itemdata.get(position).getLogo_pic(), "4"));
                    }
                });
            }

        };
        recyclerView.setAdapter(mBaseAdapter);
    }


    @Override
    public void onLeftClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = page + 1;
                loadData();
            }
        },2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 0;
                loadData();
            }
        },2000);
    }
}
